import cv2
import numpy as np
from PIL import Image
import io
import base64

def compare_images(image1_path, image2_path):
    """比较两张图像，返回相似度（0-100%）和差异图 base64 字符串"""

    # 读取图像
    img1 = cv2.imread(image1_path)
    img2 = cv2.imread(image2_path)

    # 尺寸统一
    height = min(img1.shape[0], img2.shape[0])
    width = min(img1.shape[1], img2.shape[1])
    img1 = cv2.resize(img1, (width, height))
    img2 = cv2.resize(img2, (width, height))

    # 转灰度图
    gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

    # 计算差异图
    diff = cv2.absdiff(gray1, gray2)
    _, diff_bin = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)

    # 轮廓标记差异区域
    contours, _ = cv2.findContours(diff_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    diff_vis = img2.copy()
    cv2.drawContours(diff_vis, contours, -1, (0, 0, 255), 2)

    # 计算相似度（结构相似性可选）
    similarity = 100.0 - (np.sum(diff_bin) / (255 * width * height) * 100)

    # 转 base64 编码
    _, buffer = cv2.imencode('.jpg', diff_vis)
    base64_str = base64.b64encode(buffer).decode('utf-8')

    return round(similarity, 2), base64_str
